<!--
 * @Descripttion: 开放平台-接口访问统计
 * @Author: yichao yichao@ssc-hn.com
 * @Date: 2024-09-03
 * @LastEditors: yichao yichao@ssc-hn.com
 * @LastEditTime: 2024-09-03
-->
<template>
  <div class="ssc-list org-position-list">
    <div class="ssc-search">
      <a-form :model="searchParam" autocomplete="off">
        <a-row :gutter="24">
          <a-col :span="9">
            <a-form-item label="选择日期">
              <a-range-picker v-model:value="timeRange" show-time format="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-row justify="end">
              <a-button @click="clear()">重置</a-button>
              <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
            </a-row>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="ssc-table">
      <div class="ssc-table-header">
        <span class="ssc-table-header-title"> 接口流量统计</span>
      </div>
      <!-- <realtimeEcharts /> -->
    </div>
    <div class="show_pie">
      <div class="pie_item">
        <div class="pie_title">请求总量分布（TOP10）</div>
        <PieEcharts :withdraw="currentWidth" />
      </div>
      <div class="pie_item ml-5">
        <div class="pie_title">平均响应时长分布</div>
        <PieEcharts :withdraw="currentWidth" />
      </div>
    </div>
    <div class="ssc-table">
      <div class="ssc-table-header justify-right">
        <a-button type="primary">导出</a-button>
      </div>
      <a-table :columns="columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'disable'">
            <span>{{ DisableType[record.disable] }}</span>
          </template>
          <template v-if="column.dataIndex === 'createdTime'">
            <span>{{ record.createdTime ? formatToDateTime(record.createdTime) : '--' }}</span>
          </template>
          <template v-if="column.dataIndex === 'approveTime'">
            <span>{{ record.approveTime ? formatToDateTime(record.approveTime) : '--' }}</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <span>
              <a @click="showModal(record)">请求参数</a>
              <a-divider type="vertical" />
              <a @click="showResult(record)">返回结果</a>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal v-model:visible="modalData.visible" :title="'请求参数'" :footer="null">
      <pre class="show-json" v-if="modalData.visible">{{ modalData.reqData ? modalData.reqData : '--' }}</pre>
    </a-modal>
    <a-modal v-model:visible="resultData.visible" :title="'返回结果'" :footer="null">
      <pre class="show-json" v-if="resultData.resData">{{ resultData.resData }}</pre>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import type { Dayjs } from 'dayjs'
  import { onMounted, reactive, ref, watch } from 'vue'

  import { getApplyByPageEnum } from '/@/api/manage/openApiApp'
  import { DisableType } from '/@/api/manage/openApiApp/enum'
  import { requestInterfaceRecord } from '/@/api/manage/openApiInterface'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'
  import { formatToDateTime } from '/@/utils/date'

  import realtimeEcharts from '../realtimeAccess/components/realtimeEcharts.vue'
  import PieEcharts from './components/PieEcharts.vue'
  const currentWidth = (document.documentElement.clientWidth - 260) / 2 - 30

  type RangeValue = [Dayjs, Dayjs]
  const timeRange = ref<RangeValue>()

  /** 搜索条件 */
  const searchParam = reactive<InterfaceAccessRecordApiTypes.IRequest>({
    appId: null,
    interfaceCode: null,
    startTime: null,
    endTime: null,
  })

  const modalData = reactive({
    visible: false,
    reqData: '',
  })
  const resultData = reactive({
    visible: false,
    resData: '',
  })
  const applyList = ref<any[]>([])

  /**
   * 获取订阅组列表
   */
  const queryRecordList = () => {
    return getApplyByPageEnum({ pageSize: 30, pageIndex: 1 }).then((res) => {
      applyList.value = res?.responseData.records || []
      searchParam.appId = applyList.value[0]?.appId
      search()
    })
  }
  queryRecordList()

  watch(
    timeRange,
    (value) => {
      if (value) {
        searchParam.startTime = new Date(formatToDateTime(value[0])).getTime()
        searchParam.endTime = new Date(formatToDateTime(value[1])).getTime()
      } else {
        searchParam.startTime = null
        searchParam.endTime = null
      }
    },
    { immediate: true, deep: true },
  )

  watch(
    modalData,
    (value) => {
      if (!value.visible) {
        modalData.reqData = ''
      }
    },
    { immediate: true, deep: true },
  )
  watch(
    resultData,
    (value) => {
      if (!value.visible) {
        resultData.resData = ''
      }
    },
    { immediate: true, deep: true },
  )

  /** 表格列配置 */
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      customRender: (row) => `${row.index + 1}`,
    },
    { title: '请求时间', dataIndex: 'reqTime' },
    { title: 'api接口', dataIndex: 'interfaceCode' },
    { title: '订阅组', dataIndex: 'appName' },
    { title: '状态码', dataIndex: 'resStatus' },
    { title: '响应时间', dataIndex: 'resTime', sorter: (a, b) => a.resTime - b.resTime },
    { title: '访问ip', dataIndex: 'reqIp' },
    { title: '操作', dataIndex: 'action' },
  ]

  const showModal = (data) => {
    modalData.visible = true
    modalData.reqData = data.reqData ? JSON.stringify(JSON.parse(data.reqData), null, 2) : ''
  }
  const showResult = (data) => {
    resultData.visible = true
    resultData.resData = data.resData ? JSON.stringify(JSON.parse(data.resData), null, 2) : ''
  }

  const { loading, queryList, dataList, pagination, onPaginationChange } = useQueryPagination<InterfaceAccessRecordApiTypes.IRequest, InterfaceAccessRecordApiTypes.IResponse[]>(searchParam, requestInterfaceRecord)

  onMounted(() => {
    // search()
  })

  /**
   * 重置
   */
  const clear = () => {
    searchParam.interfaceCode = null
    searchParam.startTime = null
    searchParam.endTime = null
    search()
  }

  /**
   * 搜索
   */
  const search = async () => queryList({ current: 1 })
</script>

<style lang="less" scoped>
  .show-json {
    background-color: #fbfafa;
    padding: 10px;
    border-radius: 4px;
  }

  .justify-right {
    justify-content: right !important;
  }

  .show_pie {
    display: flex;

    .pie_item {
      flex: 1;
      background-color: #fff;
      margin-top: 15px;
      border-radius: 3px;
      padding: 10px;
      box-sizing: border-box;

      .pie_title {
        font-size: 16px;
        color: #000;
        font-weight: bold;

        &::before {
          content: '';
          display: inline-block;
          width: 5px;
          height: 18px;
          border-radius: 10px;
          background-color: #409eff;
          margin-right: 5px;
          vertical-align: sub;
        }
      }
    }
  }
</style>
